package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.BaseException;
import com.sky.exception.ShopIDNotNULLException;
import com.sky.mapper.user.*;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.pojo.*;
import com.sky.result.Result;
import com.sky.service.user.UserOrderService;
import com.sky.utils.MapUtils;
import com.sky.vo.OrderSubmitVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper cartMapper;
    @Autowired
    private UserOrderMapper orderMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private MerchatMapper merchatMapper;
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
      /*  OrderSubmitVO result = new OrderSubmitVO();*/
        Orders orders = new Orders();
        //把传回来的参数（价格地址。。。存入orders中）
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //获取各种没有的信息
        orders.setNumber(UUID.randomUUID().toString().replaceAll("-",""));
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setAmount(ordersSubmitDTO.getAmount());
        orders.setStatus(Orders.PENDING_PAYMENT);
        //
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new BaseException("地址错误");
        }
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orderMapper.insert(orders);
        log.info("orders提交时的:{}",orders);
        // 制作  算时间
        Integer makeTime = cartMapper.getMakeTimeByUserId(BaseContext.getCurrentId());
        orders.setMealTime(LocalDateTime.now().plusMinutes(makeTime));


        List<ShoppingCart> shoppingCartList = cartMapper.list2(BaseContext.getCurrentId());
        log.info("购物车内容：{}",shoppingCartList);
       if(CollectionUtils.isEmpty(shoppingCartList)){
            throw new BaseException("购物车没有数据");
        }

        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,detail);
            detail.setOrderId(orders.getId());
            orderDetailList.add(detail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        OrderSubmitVO vo = OrderSubmitVO.builder().orderAmount(orders.getAmount()).orderTime(orders.getOrderTime())// .id(orders.getId())
               .orderNumber(orders.getNumber()).build();
        return vo;
    }

    @Override
    public Result<String> getgetEstimatedDeliveryTime(Integer shopId, String customerAddress) {

        //获取所有菜品的制作时间
        Long currentId = BaseContext.getCurrentId();
        Integer makeTimeCost = shoppingCartMapper.getMakeTimeByUserId(currentId);

        //计算配送地址和商家地址之间的配送时间
        Merchant merchant = merchatMapper.search((int) shopId.longValue());
        if(merchant==null){
            throw new ShopIDNotNULLException("找不到商家信息");
        }
        //工具类，直接使用
        Integer towPointCost = MapUtils.baoiduTwoPointCostTime(merchant.getShopAddress(), customerAddress);

        //预计送达时间 = 当前时间+菜品制作时间+配送时间+预留10分钟
        Integer allCost = makeTimeCost*60+towPointCost+600;
        LocalDateTime estimatedDeliveryTime = LocalDateTime.now().plusSeconds(allCost);
        return Result.success(estimatedDeliveryTime.toString());
    }

    @Override
    public void paySuccess(String number) {
        Orders orders = orderMapper.getByNumber(number);
        if (orders == null){
            log.info("订单号:{} 不存在",number);
            return;
        }
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orderMapper.updateOrderPaySuccess(orders);
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","您有新的订单了，请及时处理");
        webSocketServer.sendOrderComeReminder(JSON.toJSONString(map));
    }

    @Override
    public Result<String> reminderHurryUp(Integer orderId) {

        if ( orderMapper.selectOrderById(orderId) == null){
            return Result.error("订单号不存在，出问题了");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orderId);
        map.put("content","有用户催单了，请迅速处理");

        webSocketServer.sendOrderComeReminder(JSON.toJSONString(map));
        return Result.success();
    }
}
